package com.example.administrator.myapplication.net;

import android.text.TextUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

import javax.net.ssl.SSLSocketFactory;

public class HttpConnection {
    Socket socket;
    long lastUseTime;
    InputStream is;
    OutputStream os;
    private Request request;

    public boolean isSameAddress(String host, int port) {
        if (socket == null) {
            return false;
        }
        return TextUtils.equals(socket.getInetAddress().getHostName(), host)
                && port == socket.getPort();
    }

    public Socket getSocket() {
        return socket;
    }

    public long getLastUseTime() {
        return lastUseTime;
    }

    public void setLastUseTime(long lastUseTime) {
        this.lastUseTime = lastUseTime;
    }

    public void close() {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    /**
     * 与服务器通信
     *
     * @return
     */
    public InputStream call(HttpCodec codec) throws Exception {
        createSocket(codec);
        return is;
    }

    private void createSocket(HttpCodec codec) throws Exception{
        if (socket == null || socket.isClosed()) {
            HttpUrl url = request.url();
            if (url.protocol.equals("https")) {
                socket = SSLSocketFactory.getDefault().createSocket();
            } else {
                socket = new Socket();
            }
            socket.connect(new InetSocketAddress(url.host, url.port));

             os = socket.getOutputStream();
             codec.writeRequest(os,request);
             is = socket.getInputStream();
        }
    }
}
